package cn.com.dcsgo.controller;

import cn.com.dcsgo.order.bean.Order;
import cn.com.dcsgo.properties.OrderProperties;
import cn.com.dcsgo.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

/**
 * OrderController
 * RefreshScope注解 激活配置属性的自动刷新功能
 *
 * @author Dcsgo
 * @since 2025/3/11 9:47
 */
//@RefreshScope //使用ConfigurationProperties配置类无需再用该注解实现自动刷新
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("order")
public class OrderController {
    private final OrderService orderService;
    private final OrderProperties orderProperties;
//    @Value("${order.timeout}")
//    private String timeout;
//    @Value("${order.auto-confirm}")
//    private String autoConfirm;

    @GetMapping("create")
    public Order createOrder(@RequestParam("userId") Long userId,
                             @RequestParam("productId") Long productId) {
        return orderService.createOrder(userId, productId);
    }

    /**
     * 添加订单秒杀链路(流控模式-链路)
     *
     * @param userId    userId
     * @param productId productId
     * @return Order
     */
    @GetMapping("spikes")
    public Order spikesCreateOrder(@RequestParam("userId") Long userId,
                                   @RequestParam("productId") Long productId) {
        return orderService.createOrder(userId, productId);
    }

    /**
     * 流控模式-关联
     * 这里以读写操作为例
     * 预期是当写入请求变大时，对读请求进行限流
     * 即优先满足写请求
     * 实现：读的流控规则的模式设置为关联
     * 关联的资源就是写请求
     * 这种流控规则通常用在有竞争关系的资源，并对他们的优先级进行配置
     * 这里实现的就是写入请求优先
     * Sentinel 流量控制官方文档: https://github.com/alibaba/Sentinel/wiki/流量控制
     * @return String
     */
    @GetMapping("read")
    public String read() {
        log.info("read...");
        return "read success...";
    }

    @GetMapping("write")
    public String write() {
        return "write success...";
    }

    @GetMapping("config")
    public String getConfig() {
        String timeout = orderProperties.getTimeout();
        String autoConfirm = orderProperties.getAutoConfirm();
        return "timeout: " + timeout + " ,autoConfirm: " + autoConfirm;
    }
}
